import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Multiplex from '../../../../CreateImages/Multiplex';
import './index.css';

// 定义一个功能组件来展示标签按钮
const ShowAllButton = ({ onClick, children }) => (
  <span onClick={onClick} style={{ cursor: 'pointer', display: 'inline-block', marginBottom: '10px' }}>
    {children}
  </span>
);

// 主应用组件
const App = () => {
  // 管理从服务器获取的数据列表
  const [lists, setLists] = useState([]);
  // 控制是否显示所有项
  const [showAll, setShowAll] = useState(false);
  // 记录用户选择的类别索引
  const [selectedCategory, setSelectedCategory] = useState(null);

  // 使用副作用钩子来异步获取数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('/api/Background');
        const createWhole = response.data.data.CreateWhole;
        setLists(createWhole.map(section => section.children));
      } catch (error) {
        console.error('Failed to fetch data:', error);
      }
    };
    fetchData();
  }, []); // 空数组依赖意味着此效果只在组件挂载时运行一次

  // 处理点击“全部”时的行为
  const handleShowAllClick = index => {
    setSelectedCategory(index);
    setShowAll(true);
  };

  // 返回上一级视图
  const handleReturnClick = () => {
    setSelectedCategory(null);
    setShowAll(false);
  };

  const MasonryLayout = ({ arr }) => (
    <div className="masonry-grid">
      {arr.map((item, index) => (
        <div key={index} className="masonry-grid-item">
          <img src={item} alt="" />
        </div>
      ))}
    </div>
  );

  // 渲染不同的标签页内容
  const renderContent = () => {
    if (showAll && selectedCategory !== null) {
      return (
        <>
          <ShowAllButton onClick={handleReturnClick}>返回</ShowAllButton>
          <MasonryLayout arr={lists[selectedCategory]} />
        </>
      );
    } else {
      return lists.map((section, index) => (
        <div key={index} className='o-child'>
          <div className='o-child-box'>
            <p>{['简约背景', '复古国风', '纹理质感', '创意渐变', '商务科技', '中国红', '手绘卡通'][index]}</p>
            <ShowAllButton onClick={() => handleShowAllClick(index)}>全部</ShowAllButton>
          </div>
          {/* 只显示前三个元素作为示例 */}
          <Multiplex arr={section.slice(0, 3)} />
        </div>
      ));
    }
  };

  return (
    <div className='e-boxx'>
      <div className='setdata'>
        <div className='n-tabs'>
          {renderContent()}
        </div>
      </div>
    </div>
  );
};

export default App;